function getParameterByName(name, url = window.location.href) {
    name = name.replace(/[\[\]]/g, '\\$&');
    const regex = new RegExp(`[?&]${name}(=([^&#]*)|&|#|$)`);
    const results = regex.exec(url);
    if (!results) return null;
    if (!results[2]) return '';
    return decodeURIComponent(results[2].replace(/\+/g, ' '));
}

const uroot = getParameterByName('uroot');
const root = parseInt(uroot, 10);

var uid = getParameterByName('uid');
const id = parseInt(uid, 10);

var cname = getParameterByName('uname');

// 分页状态管理
let currentPage = 1;
let totalPages = 1;
const pageSize = 10;
let allData = [];

const statusMap = {
    0: '未售出',  // 假设后端返回0表示未售出
    1: '已售出'   // 假设后端返回1表示已售出
};

// 全局变量
let sortConfig = {
    currentSortField: null,
    isAscending: true,
    field: null,      // 当前排序字段
    direction: 1,    // 1: 升序, -1: 降序
    type: 'auto'

};

// 初始化加载
document.addEventListener('DOMContentLoaded', () => {
    showPage('carListPage');
    loadAllData();
    document.getElementById('searchBtn').addEventListener('click', () => {
        currentPage = 1;
        filterData();
    });

    // 添加输入框的实时监听
    document.getElementById('cname').addEventListener('input', () => {
        currentPage = 1;
        filterData();
    });

    // 设置默认的起始时间和结束时间
    const today = new Date();
    const startDate = new Date('2024-11-01');
    document.getElementById('startTime').valueAsDate = startDate;
    document.getElementById('endTime').valueAsDate = today;
    document.getElementById('searchBtn').addEventListener('click', () => {
        currentPage = 1;
        filterData();
    });
    // 初始化时自动触发查询
    loadAllData().then(() => {
        // 确保至少触发一次过滤
        document.getElementById('searchBtn').click();
    });

    // 使用 data-sort-field 和 data-sort-type 定义可排序列
    document.querySelectorAll('th[data-sort-field]').forEach(header => {
        header.style.cursor = 'pointer';
        header.addEventListener('click', () => {
            const field = header.dataset.sortField;
            const dataType = header.dataset.sortType || 'auto';
            handleSort(field, dataType);
        });
    });
});

function handleSort(field, dataType) {
    // 判断是否切换字段
    if (sortConfig.field !== field) {
        sortConfig.field = field;
        sortConfig.direction = 1; // 新字段默认升序
        sortConfig.type = dataType;
    } else {
        sortConfig.direction *= -1; // 相同字段切换方向
    }

    // 更新UI指示器
    updateSortIndicator();

    // 触发数据更新
    filterData();
}


// ================== UI指示器更新 ==================
function updateSortIndicator() {
    // 清除所有指示器
    document.querySelectorAll('th[data-sort-field]').forEach(header => {
        header.querySelector('.sort-indicator')?.remove();
    });

    if (!sortConfig.field) return;

    // 添加新指示器
    const activeHeader = document.querySelector(`th[data-sort-field="${sortConfig.field}"]`);
    if (activeHeader) {
        const indicator = document.createElement('span');
        indicator.className = 'sort-indicator';
        indicator.textContent = sortConfig.direction === 1 ? '↑' : '↓';
        indicator.style.marginLeft = '5px';
        activeHeader.appendChild(indicator);
    }
}

// 加载全部数据
async function loadAllData() {
    try {
        const response = await fetch('http://127.0.0.1:8080/selectcarall');
        if (!response.ok) {
            throw new Error(`HTTP错误 ${response.status}`);
        }
        allData = await response.json();
        filterData();
    } catch (error) {
        console.error('加载数据失败:', error);
        showError('加载数据失败，请检查网络连接或URL是否正确');
    }
}

// 排序功能
function sortTable(field) {
    if (sortConfig.currentSortField === field) {
        sortConfig.isAscending = !sortConfig.isAscending;
    } else {
        sortConfig.currentSortField = field;
        sortConfig.isAscending = true;
    }

    // 重新过滤和渲染数据
    filterData();
}

// 增强版过滤逻辑
function filterData() {
    const storageValue = document.getElementById('storage').value;
    const cnameValue = document.getElementById('cname').value.toLowerCase();
    const creatorValue = document.getElementById('creator').value.toLowerCase(); // 新增创建人筛选
    const statusValue = document.getElementById('status').value; // 新增状态筛选
    const startTimeValue = document.getElementById('startTime').value;
    const endTimeValue = document.getElementById('endTime').value;

    const filteredData = allData.filter(car => {
        const carDate = car.time ? new Date(car.time) : null;
        const startDate = startTimeValue ? new Date(startTimeValue) : null;
        const endDate = endTimeValue ? new Date(endTimeValue) : null;

        // 修正状态筛选逻辑，使其与第一个文件一致
        const statusCondition = !statusValue || car.status === statusValue;

        return (
            (!storageValue || car.storage === storageValue) &&
            (!cnameValue || car.cname.toLowerCase().includes(cnameValue)) &&
            (!creatorValue || car.creator.toLowerCase().includes(creatorValue)) &&
            statusCondition &&
            (!startDate || (carDate && carDate >= startDate)) &&
            (!endDate || (carDate && carDate <= endDate))
        );
    });

    // 排序
    if (sortConfig.currentSortField) {
        filteredData.sort((a, b) => {
            if (sortConfig.currentSortField === 'time') {
                return sortConfig.isAscending
                    ? new Date(a.time) - new Date(b.time)
                    : new Date(b.time) - new Date(a.time);
            } else if (sortConfig.currentSortField === 'cid') {
                return sortConfig.isAscending
                    ? parseInt(a.cid) - parseInt(b.cid)
                    : parseInt(b.cid) - parseInt(a.cid);
            }
            return 0;
        });
    }

    totalPages = Math.max(1, Math.ceil(filteredData.length / pageSize));
    currentPage = Math.min(currentPage, totalPages);
    currentPage = Math.max(currentPage, 1);

    renderTable(filteredData);
    renderSmartPagination();
}

// 获取仓库名称
function getStorageName(storageId) {
    const storageOptions = {
        '1': '西安仓库',
        '2': '北京仓库',
        '3': '上海仓库'
    };
    return storageOptions[storageId] || '';
}


// 修改后的表格渲染逻辑
function renderTable(data) {
    const tbody = document.getElementById('carList');
    tbody.innerHTML = '';

    if (!Array.isArray(data)) {
        showError('数据格式错误');
        return;
    }

    if (data.length === 0) {
        document.getElementById('noDataMessage').textContent = '没有找到相关数据';
        return;
    }

    // 保持原有渲染逻辑
    const start = (currentPage - 1) * pageSize;
    const pageData = data.slice(start, start + pageSize);

    pageData.forEach(car => {
        const row = document.createElement('tr');
        row.innerHTML = `
      <td>${car.cid || '--'}</td>
      <td>${car.cname || '--'}</td>
      <td>${car.color || '--'}</td>
      <td>${car.price} 元</td>
      <td>${car.storage || '未分配'}</td>
      <td>${formatDate(car.time)}</td>
      <td>${car.status || '未知状态'}</td>
      <td>${car.creator || '系统'}</td>
      <td>
    ${car.status === '未售出' ? `<button class="operation-btn" onclick="confirmStorage(${car.cid})">确认出库</button>` : '已完成'}
      </td>
    `;
        tbody.appendChild(row);
    });

    // 隐藏“没有找到相关数据”提示
    document.getElementById('noDataMessage').textContent = '';
}

// 智能分页渲染
function renderSmartPagination() {
    const paginationDiv = document.getElementById('pagination');
    paginationDiv.innerHTML = '';

    if (totalPages <= 1) return;

    // 上一页按钮
    const prevButton = createPageButton('‹', currentPage > 1, () => {
        currentPage--;
        updatePagination();
    });
    paginationDiv.appendChild(prevButton);

    // 计算页码范围
    let startPage = Math.max(1, currentPage - 2);
    let endPage = Math.min(totalPages, currentPage + 2);

    if (currentPage <= 3) {
        endPage = Math.min(5, totalPages);
    } else if (currentPage >= totalPages - 2) {
        startPage = Math.max(1, totalPages - 4);
    }

    // 显示首部
    if (startPage > 1) {
        paginationDiv.appendChild(createPageButton(1));
        if (startPage > 2) {
            paginationDiv.appendChild(createEllipsis());
        }
    }

    // 主按钮区
    for (let i = startPage; i <= endPage; i++) {
        paginationDiv.appendChild(createPageButton(i));
    }

    // 显示尾部
    if (endPage < totalPages) {
        if (endPage < totalPages - 1) {
            paginationDiv.appendChild(createEllipsis());
        }
        paginationDiv.appendChild(createPageButton(totalPages));
    }

    // 下一页按钮
    const nextButton = createPageButton('›', currentPage < totalPages, () => {
        currentPage++;
        updatePagination();
    });
    paginationDiv.appendChild(nextButton);

    // 添加跳转功能
    const jumpBox = document.createElement('div');
    jumpBox.className = 'page-jump-box';
    const input = document.createElement('input');
    input.className = 'page-jump-input';
    input.type = 'number';
    input.min = '1';
    input.max = totalPages;
    input.placeholder = '页数';
    input.value = currentPage;

    const jumpBtn = document.createElement('button');
    jumpBtn.className = 'page-jump-btn';
    jumpBtn.textContent = '跳转';

    // 绑定跳转按钮的点击事件
    jumpBtn.addEventListener('click', () => {
        const page = parseInt(input.value);
        if (page >= 1 && page <= totalPages) {
            currentPage = page;
            updatePagination();
        } else {
            showError('请输入有效的页码');
        }
    });

    // 回车键支持
    input.addEventListener('keypress', (e) => {
        if (e.key === 'Enter') {
            jumpBtn.click();
        }
    });

    jumpBox.appendChild(input);
    jumpBox.appendChild(jumpBtn);
    paginationDiv.appendChild(jumpBox);
}

// 创建分页按钮
function createPageButton(text, active = true, clickHandler) {
    const button = document.createElement('button');
    button.className = `page-btn ${text === currentPage ? 'active' : ''}`;
    button.textContent = text;
    button.disabled = !active;
    if (typeof text === 'number') {
        button.onclick = () => {
            currentPage = text;
            updatePagination();
        };
    } else if (clickHandler) {
        button.onclick = clickHandler;
    }
    return button;
}

// 创建省略号
function createEllipsis() {
    const span = document.createElement('span');
    span.className = 'page-ellipsis';
    span.textContent = '...';
    return span;
}

// 更新分页状态
function updatePagination() {
    filterData();
    window.scrollTo({top: 0, behavior: 'smooth'});
}

// 工具函数
function formatDate(dateString) {
    if (!dateString) return '--';
    try {
        const date = new Date(dateString);
        return new Intl.DateTimeFormat('zh-CN', {
            year: 'numeric',
            month: '2-digit',
            day: '2-digit',
            hour: '2-digit',
            minute: '2-digit',
            second: '2-digit'
        }).format(date);
    } catch (e) {
        console.error('日期格式错误:', dateString);
        return '无效日期';
    }
}

function formatNumber(num) {
    if (isNaN(Number(num))) return '0.00';
    return new Intl.NumberFormat('zh-CN', {
        style: 'decimal',
        minimumFractionDigits: 2,
        maximumFractionDigits: 2
    }).format(num);
}


function showError(message) {
    alert(`错误: ${message}`);
    document.getElementById('errorMessage').textContent = ''; // 清空原有错误区域
    const messageBox = document.getElementById('batchInsertMessage');
    messageBox.textContent = message;
    messageBox.className = 'message-box error';
}

// 强化出库操作
let preservedPage = 1;

function confirmStorage(cid) {
    if (confirm(`确定要出库账单号 ${cid} 的车辆吗？`)) {
        // 发送请求到后端更新状态
        fetch(`http://127.0.0.1:8080/updatecarstatus?cid=${cid}`, {
            method: 'GET'
        })
            .then(response => {
                if (!response.ok) {
                    throw new Error(`HTTP错误 ${response.status}`);
                }
                return response.text();
            })
            .then(data => {
                if (data.includes('成功')) {
                    const index = allData.findIndex(item => item.cid === cid);
                    if (index !== -1) {
                        allData[index].status = 1;
                        filterData();
                    }
                    showSuccessMessage(data);
                } else {
                    throw new Error(data || '操作失败');
                }
            })
            .catch(error => {
                showError(error.message);
            });
    }
}

// 页面切换逻辑
function showPage(pageId) {
    document.getElementById('carListPage').style.display = 'none';
    document.getElementById('userStatsPage').style.display = 'none';
    document.getElementById(pageId).style.display = 'block';

    // 更新侧边栏选中状态
    const sidebarItems = document.querySelectorAll('.sidebar li');
    sidebarItems.forEach(item => item.classList.remove('active'));
    const selectedItem = document.querySelector(`.sidebar li[onclick="showPage('${pageId}')"]`);
    if (selectedItem) selectedItem.classList.add('active');

    // 如果是员工账单页面，加载数据
    if (pageId === 'userStatsPage') {
        loadUserStats();
    }
}

// 加载用户统计信息
async function loadUserStats() {
    try {
        const response = await fetch('http://127.0.0.1:8080/countUserprice');
        if (!response.ok) {
            throw new Error(`HTTP错误 ${response.status}`);
        }
        const data = await response.json();
        renderUserPriceTable(data);
    } catch (error) {
        console.error('加载用户统计信息失败:', error);
        showError('加载用户统计信息失败，请检查网络连接或URL是否正确');
    }
}


// 渲染用户统计表格
function renderUserPriceTable(data) {
    const tbody = document.getElementById('userStatsList');
    tbody.innerHTML = '';

    if (!Array.isArray(data)) {
        showError('数据格式错误');
        return;
    }

    if (data.length === 0) {
        const row = document.createElement('tr');
        row.innerHTML = '<td colspan="6" style="text-align: center;">没有找到相关数据</td>';
        tbody.appendChild(row);
        return;
    }

    data.forEach(item => {
        const row = document.createElement('tr');
        row.innerHTML = `
      <td>${item.uid}</td>
      <td>${item.creator}</td>
      <td>${item.creator_count_status_1}</td>
      <td>${item.creator_count_status_1_percentage.toFixed(2)}%</td>
      <td>${item.total_quantity_status_1}</td>
      <td>${item.total_value_status_1} 元</td>
    `;
        tbody.appendChild(row);
    });
}

function showSuccessMessage(message) {
    alert(`成功: ${message}`);
    const messageBox = document.getElementById('batchUpdateMessage');
    messageBox.textContent = message;
    messageBox.className = 'message-box success';
}

document.getElementById('batchInsertBtn').addEventListener('click', function () {
    const cidsInput = document.getElementById('batchCids').value.trim();
    if (!cidsInput) {
        showError('请输入cid');
        return;
    }

    // 解析输入的cid列表
    const cids = cidsInput.split(',').map(function (cid) {
        return cid.trim();
    }).filter(function (cid) {
        return cid !== '';
    });

    if (cids.length === 0) {
        showError('请输入有效的cid');
        return;
    }

    // 批量插入
    batchInsertCids(cids);
});

function batchInsertCids(cids) {
    let successCount = 0;
    let failureCount = 0;
    let alreadySoldCount = 0;
    const failedCids = [];
    const invalidCids = [];
    const alreadySoldCids = [];
    const promises = [];

    cids.forEach(cid => {
        // 新增：检查CID是否为数字
        if (isNaN(parseInt(cid))) {
            invalidCids.push(cid);
            return; // 跳过非数字CID
        }
        const car = allData.find(item => item.cid === parseInt(cid));
        if (car && car.status === '已售出') {
            alreadySoldCount++;
            alreadySoldCids.push(cid);
            return;
        }

        promises.push(
            insertCarStatus(cid)
                .then(response => {
                    if (response && response.success) {
                        successCount++;
                    } else {
                        failureCount++;
                        failedCids.push(cid);
                    }
                })
                .catch(error => {
                    failureCount++;
                    failedCids.push(cid);
                    console.error('插入失败:', error);
                })
        );
    });

    Promise.allSettled(promises).then(() => {
        // 传递非数字CID列表给结果函数
        showBatchInsertResult(successCount, failureCount, alreadySoldCount, failedCids, alreadySoldCids, invalidCids);
    });
}

function insertCarStatus(cid) {
    return fetch('http://127.0.0.1:8080/insertCarStatus?cid=' + cid, {
        method: 'POST',
        headers: {
            'Content-Type': 'application/json',
        },
    })
        .then(function (response) {
            if (!response.ok) {
                throw new Error('HTTP错误 ' + response.status);
            }
            return response.json();
        })
        .catch(function (error) {
            throw new Error(error.message);
        });
}

function showLoading(message) {
    const messageBox = document.getElementById('batchInsertMessage');
    messageBox.textContent = message;
    messageBox.className = 'message-box loading';
}

function showBatchInsertResult(successCount, failureCount, alreadySoldCount, failedCids, alreadySoldCids, invalidCids) {
    const messageBox = document.getElementById('batchInsertMessage');
    messageBox.className = 'message-box result';

    if (successCount > 0 && failureCount === 0 && alreadySoldCount === 0) {
        messageBox.textContent = '批量操作成功';
        messageBox.className += ' success';
    } else {
        let message = '';
        if (successCount > 0) {
            message += `已成功操作 ${successCount} 条数据。   `;
        }
        if (alreadySoldCount > 0) {
            message += `账单号为 ${alreadySoldCids.join(', ')} 的车辆已售出，请检查账单号无误后再操作。   `;
        }
        if (failureCount > 0) {
            message += `修改失败 ${failureCount} 条：没有找到账单号为 ${failedCids.join(', ')} 的账单，请检查账单号无误后再操作。`;
        }
        // 新增非数字提示
        if (invalidCids.length > 0) message += `账单号 ${invalidCids.join(', ')} 格式错误（必须为数字），请检查账单号无误后再操作。`;

        messageBox.textContent = message;
        messageBox.className += ' warning';
    }

    // 刷新列表
    loadAllData();
}